package com.tadpole.music.view.activity.study;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tadpole.music.R;
import com.tadpole.music.adapter.base.BaseAdapter;
import com.tadpole.music.adapter.study.AnswerStatisticsAdapter;
import com.tadpole.music.adapter.study.ErrorTopicAdapter;
import com.tadpole.music.adapter.study.MoNiErrorAdapter;
import com.tadpole.music.bean.question.QuestionClassBean;
import com.tadpole.music.bean.question.QuestionRankBean;
import com.tadpole.music.bean.question.UniversityBean;
import com.tadpole.music.bean.study.MoNiQuestionErrorBean;
import com.tadpole.music.bean.study.MyExamsFootBean;
import com.tadpole.music.bean.study.MyExamsHeadBean;
import com.tadpole.music.bean.study.QuestionBean;
import com.tadpole.music.bean.study.QuestionCountHeadBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.question.QuestionClassIView;
import com.tadpole.music.iView.question.QuestionRankIView;
import com.tadpole.music.iView.question.UniversityIView;
import com.tadpole.music.iView.study.MoNiQuestionErrorIView;
import com.tadpole.music.iView.study.MyExamsIView;
import com.tadpole.music.iView.study.QuestionCountIView;
import com.tadpole.music.presenter.question.QuestionClassPresenter;
import com.tadpole.music.presenter.question.QuestionRankPresenter;
import com.tadpole.music.presenter.question.UniversityPresenter;
import com.tadpole.music.presenter.study.MoNiQuestionErrorPresenter;
import com.tadpole.music.presenter.study.MyExamsPresenter;
import com.tadpole.music.presenter.study.QuestionCountPresenter;
import com.tadpole.music.utils.DateUtils;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.StatusBarUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.activity.question.RealTrainActivity;
import com.tadpole.music.view.activity.question.SimulationPracticeActivity;
import com.tadpole.music.view.widget.MyRecyclerViewDivider;
import com.tadpole.music.view.widget.NiceImageView;
import com.tadpole.music.view.widget.ScreenDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


import uk.co.deanwild.materialshowcaseview.MaterialShowcaseView;
import uk.co.deanwild.materialshowcaseview.shape.OvalShape;

/**
 * 答题统计
 * Created By 孙岩
 * on 2020/9/10
 */
public class AnswerStatisticsActivity extends BaseActivity implements UniversityIView, QuestionRankIView, QuestionClassIView, QuestionCountIView, MyExamsIView, MoNiQuestionErrorIView {
    private static final String SHOWCASE_ID = "0x001";
    //回退
    private View view_back_icon;
    //筛选
    private View viewScreen;
    //头像
    private NiceImageView ivImage;
    //学院名称
    private TextView tvName;

    private TextView tvClassName;
    //正确率
    private TextView tvAccuracy;
    //答题时长
    private TextView tvAnswerTime;
    //考试详情 recyclerView
    private RecyclerView recyclerView;
    //刷新
    private SmartRefreshLayout rl_refresh;
    //答题统计的adapter 真题实战
    private AnswerStatisticsAdapter answerStatisticsAdapter;
    //答题统计 模拟测试
    private MoNiErrorAdapter moNiErrorAdapter;
    //获取学院的presenter
    private UniversityPresenter universityPresenter;
    //学院的数据
    private List<UniversityBean.DataBean> collegeList;

    //选择题目的数据
    private List<QuestionBean> questionList = new ArrayList<>();

    //等级 presenter
    private QuestionRankPresenter questionRankPresenter;
    //等级数据
    private List<QuestionRankBean.DataBean> rankList;

    //分类presenter
    private QuestionClassPresenter questionClassPresenter;
    //分类数据
    private List<QuestionClassBean.DataBean> classList;

    //获取头部数据
    private QuestionCountPresenter questionCountPresenter;

    //模拟训练错题的presenter
    private MoNiQuestionErrorPresenter moNiQuestionErrorPresenter;

    //实战真题
    private MyExamsPresenter myExamsPresenter;
    //1是实战 2是模拟
    private int flag = 1;
    //学院id
    private String college_id;
    //等级id
    private int rank_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer_statistice);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //将头部状态栏置为透明
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        initViews();
        initListeners();

        //获取学院
        universityPresenter = new UniversityPresenter();
        universityPresenter.attachView(this);
        universityPresenter.getUniversity();

        //获取选择题目
        questionList.add(new QuestionBean("实战真题", false));
        questionList.add(new QuestionBean("模拟训练", false));

        //获取等级
        questionRankPresenter = new QuestionRankPresenter();
        questionRankPresenter.attachView(this);

        //获取分类
        questionClassPresenter = new QuestionClassPresenter();
        questionClassPresenter.attachView(this);

        //头部数据
        questionCountPresenter = new QuestionCountPresenter();
        questionCountPresenter.attachView(this);

        //实战真题foot
        myExamsPresenter = new MyExamsPresenter();
        myExamsPresenter.attachView(this);

        //模拟训练错题
        moNiQuestionErrorPresenter = new MoNiQuestionErrorPresenter();
        moNiQuestionErrorPresenter.attachView(this);

        new MaterialShowcaseView.Builder(this)
                .setTarget(viewScreen)
                .setDismissText("知道了")
                .setContentText("新增筛选功能！！！")
                .renderOverNavigationBar()
                .setDismissOnTouch(true)
                .setDelay(500) // optional but starting animations immediately in onCreate can make them choppy
                //.singleUse(SHOWCASE_ID) 唯一标识
                .show();
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        viewScreen = findViewById(R.id.viewScreen);
        ivImage = findViewById(R.id.ivImage);
        tvName = findViewById(R.id.tvName);
        tvAccuracy = findViewById(R.id.tvAccuracy);
        tvAnswerTime = findViewById(R.id.tvAnswerTime);
        recyclerView = findViewById(R.id.recyclerView);
        tvClassName = findViewById(R.id.tvClassName);
        rl_refresh = findViewById(R.id.rl_refresh);


    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                AnswerStatisticsActivity.this.finish();
            }
        });

        //筛选
        viewScreen.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    final ScreenDialog dialog = new ScreenDialog(AnswerStatisticsActivity.this, R.style.Dialog_NoTitle);
                    dialog.show();
                    dialog.setScreenListener(new ScreenDialog.IScreen() {
                        @Override
                        public void getScreenMode(int mode, int college_id, String college_name, int rank_id, int class_id, String class_name, int q_type) {
                            AnswerStatisticsActivity.this.college_id = String.valueOf(college_id);
                            if (q_type == 1) {
                                flag = 2;
                                moNiQuestionErrorPresenter.getMoNiError(String.valueOf(college_id), true, 1, "");
                            } else if (q_type == 2) {
                                flag = 1;
                                myExamsPresenter.getExamsFoot(String.valueOf(college_id), true);
                            }

                            AnswerStatisticsActivity.this.rank_id = rank_id;
                            questionCountPresenter.getQuestionCountHead(college_name, class_name, String.valueOf(college_id), String.valueOf(rank_id), String.valueOf(class_id), String.valueOf(q_type));

                            dialog.dismiss();
                        }
                    });
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //添加刷新监听器
        rl_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@io.reactivex.annotations.NonNull RefreshLayout refreshLayout) {
                if (flag == 1) {
                    myExamsPresenter.getExamsFoot(college_id, true);
                } else if (flag == 2) {
                    moNiQuestionErrorPresenter.getMoNiError(college_id, true, 1, "");
                }
            }
        });

        //上拉加载
        rl_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@androidx.annotation.NonNull RefreshLayout refreshLayout) {
                if (flag == 1) {
                    myExamsPresenter.getExamsFootMore(college_id);
                } else if (flag == 2) {
                    moNiQuestionErrorPresenter.getMoNiErrorMore(college_id, 1, "");
                }
            }
        });
    }

    //学院回调
    @Override
    public void showUniversity(List<UniversityBean.DataBean> list) {
        if (list != null && list.size() != 0) {
            this.collegeList = list;
            college_id = String.valueOf(list.get(0).getId());
            questionRankPresenter.getQuestionRank(list.get(0).getId());

            if (flag == 1) {
                myExamsPresenter.getExamsFoot(String.valueOf(list.get(0).getId()), false);
            }
        }

    }

    //等级回调
    @Override
    public void showQuestionRank(List<QuestionRankBean.DataBean> list) {
        if (list != null && list.size() != 0) {
            this.rankList = list;
            rank_id = list.get(0).getId();
            questionClassPresenter.getQuestion_class(String.valueOf(list.get(0).getCollege_id()), String.valueOf(list.get(0).getId()));
        }
    }

    //分类回调
    @Override
    public void showQuestionClass(List<QuestionClassBean.DataBean> list) {
        if (list != null && list.size() != 0) {
            this.classList = list;
        }
        questionCountPresenter.getQuestionCountHead(collegeList.get(0).getName(), classList.get(0).getName(), String.valueOf(collegeList.get(0).getId()), String.valueOf(rankList.get(0).getId()), String.valueOf(classList.get(0).getId()), "2");

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void showQuestionCount(QuestionCountHeadBean.DataBean bean, String college_name, String class_name) {
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.app_icon)
                .error(R.mipmap.app_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);

        if (SpUtil.getInstance(this).getString(Constant.USER_AVATAR, "").equals("")) {
            Glide.with(Objects.requireNonNull(this)).load(R.mipmap.app_icon).apply(requestOptions).into(ivImage);
        } else {
            Glide.with(Objects.requireNonNull(this)).load(SpUtil.getInstance(this).getString(Constant.USER_AVATAR, "")).apply(requestOptions).into(ivImage);
        }

        if (SpUtil.getInstance(this).getString(Constant.USER_NICKNAME, "").equals("")) {
            tvName.setText("蝌蚪音基会员");
        } else {
            tvName.setText(SpUtil.getInstance(this).getString(Constant.USER_NICKNAME, ""));
        }

        tvClassName.setText(college_name);

        tvName.setText(class_name);

        if (bean.getRate().equals("NaN")) {
            tvAccuracy.setText("0");
        } else {
            tvAccuracy.setText((new BigDecimal(Double.parseDouble(bean.getRate()) * 100).setScale(2, BigDecimal.ROUND_UP).doubleValue()) + "");
        }

        if (bean.getTime().equals("NaN")) {
            tvAnswerTime.setText("0");
        } else {
            tvAnswerTime.setText(bean.getTime());
        }
    }

    @Override
    public void showExamsHead(MyExamsHeadBean.DataBean bean) {

    }

    //实战真题错题
    @Override
    public void showExamsFoot(final List<MyExamsFootBean.DataBeanX.DataBean> list) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        answerStatisticsAdapter = new AnswerStatisticsAdapter(this, list, 2);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(answerStatisticsAdapter);

        answerStatisticsAdapter.setOnChildClickListener(new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(View v, int position) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(AnswerStatisticsActivity.this).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(AnswerStatisticsActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        if (v.getId() == R.id.tvAgain) {//重新测试
                            Intent intent = new Intent(AnswerStatisticsActivity.this, RealTrainActivity.class);
                            intent.putExtra("name", list.get(position).getCollege());
                            intent.putExtra("id", list.get(position).getCollege_id());
                            intent.putExtra("rank_id", list.get(position).getRank_id());
                            startActivity(intent);
                        } else if (v.getId() == R.id.tvSeeError) {//查看错题
                            Intent intent = new Intent(AnswerStatisticsActivity.this, ErrorExamActivity.class);
                            intent.putExtra("id",list.get(position).getId());
                            intent.putExtra("flag","1");
                            startActivity(intent);
                            startActivity(intent);
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        answerStatisticsAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

            }
        });
    }

    //模拟训练错题
    @Override
    public void showQuestion(final List<MoNiQuestionErrorBean.DataBeanX.DataBean> list) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        moNiErrorAdapter = new MoNiErrorAdapter(this, list);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(moNiErrorAdapter);

        moNiErrorAdapter.setOnChildClickListener(new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(View v, int position) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(AnswerStatisticsActivity.this).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(AnswerStatisticsActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        if (v.getId() == R.id.tvAgain) {//重新测试
                            Intent intent = new Intent(AnswerStatisticsActivity.this, SimulationPracticeActivity.class);
                            intent.putExtra("id", Integer.valueOf(college_id));
                            intent.putExtra("name", list.get(position).getCollege());
                            intent.putExtra("rank_id", rank_id);
                            startActivity(intent);
                        } else if (v.getId() == R.id.tvSeeError) {//查看错题
                            Intent intent = new Intent(AnswerStatisticsActivity.this, ErrorActivity.class);
                            intent.putExtra("id", list.get(position).getId());
                            intent.putExtra("flag", "1");
                            startActivity(intent);
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void notifyAdapter() {
        if (answerStatisticsAdapter != null) {
            answerStatisticsAdapter.notifyDataSetChanged();
        }

        if (moNiErrorAdapter != null) {
            moNiErrorAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void stopRefresh() {
        rl_refresh.finishRefresh();
        rl_refresh.finishLoadMore();

    }

    @Override
    public void show401() {
        SpUtil.getInstance(this).getString(Constant.TOKEN, "");
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }
}
